'use strict';

define(['angular', 'angular-ui-router', '../../common/utils/service'], function (angular) {
	var module = angular.module('login', ['ui.router', 'dataService']);
	module.config(['$stateProvider', function ($stateProvider) {
		$stateProvider
			.state("login", {
				url: '/login',
				controller: 'LoginCtrl',
				templateUrl: '/mstore/login/login.html'
			})
	}]);

	module.controller('LoginCtrl', ['$state', '$rootScope', '$scope', 'growl', '$interval', 'dataService', function ($state, $rootScope, $scope, growl, $interval, dataService) {
		if (sessionStorage.memberId) {
			$state.transitionTo('member');
		}

		Promise.promisify(dataService.getStoreConfig)(sessionStorage.store, 'member.defaultRegisterMemberType').then(function (data) {
			if (!data) {
				throw data;
			}
			if (data.value == 'null') {
				throw data;
			} else {
				$scope.isHasRegister = true;
				$scope.$apply();
			}

		}).catch(function (err) {
			$scope.isHasRegister = false;
		});

		$scope.formSubmit = function () {
			if ($scope.isSendCode) {
				$scope.login($scope.sendData.mobile, $scope.sendData.code);
			} else {
				$scope.sendCode($scope.sendData.mobile);
			}
		}
		$scope.sendData = {};
		$scope.sendData.code = '';
		$scope.isSendCode = false;
		$rootScope.pageTitle = "登录";
		$scope.sendData.mobile = '';
		var storeId = sessionStorage.store;
		$scope.storeInfo = sessionStorage.storeInfo && JSON.parse(sessionStorage.storeInfo);
		$scope.sendCode = function (mobile) {
			var againStr = '再次发送动态登录密码',
				resendInterval = 60,
				cooldown = false;
			var account = {account: mobile};
			if (!/^((13[0-9])|(15[^4,\D])|(18[0-9])|(14[0-9])|(17[0,6-8]))\d{8}$/.test(mobile)) {
				return $rootScope.showMessage('号码格式有误，请输入正确的号码');
			}

			if (cooldown) {
				return;
			}

			cooldown = true;

			dataService.sendMemberBindSmsCode(storeId, account, function (err) {
				if (err) {
					return $rootScope.showMessage(err.msg.error);
				}
				$rootScope.showMessage('动态登录密码已发送手机"' + mobile + '"');
				$scope.smsBlocked = true;
				$scope.againTime = resendInterval;
				$scope.isSendCode = true;
				var intervalHandler = $interval(function () {
					$scope.againTime--;
					if ($scope.againTime == 0) {
						$scope.smsBlocked = false;
						$interval.cancel(intervalHandler);
						cooldown = false;
					}
				}, 1000);
			});
		}
		$scope.login = function (mobile, code) {
			if (!mobile) {
				return $rootScope.showMessage('号码格式有误，请输入正确的号码');
			}
			if (!code) {
				return $rootScope.showMessage('输入的动态登录密码有误！');
			}
			var data = {sns: sessionStorage.sns, openId: sessionStorage.openId, account: mobile, verficationCode: code};
			dataService.bindMember(storeId, data, function (err, value) {
				if (err) {
					if (value) {
						$rootScope.showMessage(value.error);
					} else {
						$rootScope.showMessage(err.msg);
					}
					return;
				}
				$scope.bindMember(value.id);
				$state.transitionTo(sessionStorage.loginBackState || 'member');
			})
		}

	}]);
});
